When you run a Java program, Java needs memory to:
Imagine your computer is a house:
String name = new String("Deepak");
๐ Result: "Deepak" is stored in Heap
int a = 10;
๐ Result: 'a' is a local variable, stored in Stack
static int collegeCode = 123;
๐ Result: 'collegeCode' is stored in the Method Area
public class Student { int age = 20; // Stored in Heap static String school = "ABC"; // Stored in Method Area public static void main(String[] args) { int roll = 101; // Stored in Stack Student s1 = new Student(); // Object in Heap, ref in Stack } }
Memory Area | What It Stores |
---|---|
Heap | Object s1, instance variable age |
Stack | roll, reference to s1 |
Method Area | Class info, school |
free()
like in C/C++Student s1 = new Student();
s1 = null; // Now the object is not used โ eligible for GC
You can suggest GC like this:
System.gc(); // Suggests garbage collection (not guaranteed)
โ Question | โ Simple Answer |
---|---|
What is memory management? | Java automatically allocates and frees memory using JVM. |
What is the Heap? | Stores objects. Shared by all. Cleaned by garbage collector. |
What is Stack memory? | Stores method calls and local variables. One per thread. |
What is garbage collection? | JVM removes unused objects from memory automatically. |
Where are static variables stored? | In the Method Area. |
What is stored in Stack vs Heap? | Stack = local vars, refs. Heap = objects. |
Can you force GC in Java? | You can suggest it using System.gc(), but it's not guaranteed. |
Part | Description | Example |
---|---|---|
Heap | Stores objects | new Student() |
Stack | Stores method calls and variables | int a = 5; |
Method Area | Stores class data, static vars | static int x; |
Garbage Collection | Removes unused objects | obj = null; |